

import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:oral_cloud/model/medical_imaging.dart';
import 'package:oral_cloud/provider/view_state_list_model.dart';
import 'package:oral_cloud/service/oral_repository.dart';

class MedicalImageModel extends ViewStateListModel {
  final String token;
  final int patientId;
  MedicalImageModel(this.token, this.patientId);

  @override
  Future<List<MedicalImaging>> loadData() async {
    List<MedicalImaging> datas=await OralRepository.fetchPatientPicList(token, patientId);
    for (MedicalImaging info in datas) {
      List<dynamic> taskList = await FlutterDownloader.loadTasksWithRawQuery(
          query: "SELECT * FROM task WHERE id='${info.group}' ");
      if(taskList.length==0){
        continue;
      }
      int successCount=0;
      int failCount=0;
      int runningCount=0;
      for(DownloadTask task in taskList){
        if(task.status==DownloadTaskStatus.complete){
          successCount++;
        }
        else if(task.status==DownloadTaskStatus.failed){
          failCount++;
        }
        else if(task.status==DownloadTaskStatus.running){
          runningCount++;
        }
      }
      int totalLength=info.imageList.length;
      print('loadData successCount:$successCount,failCount:$failCount,runningCount:$runningCount,taskList.length=$totalLength');
      if(successCount==totalLength){
        info.status=DownloadTaskStatus.complete;
      }else if((failCount+successCount)==totalLength){
        info.status=DownloadTaskStatus.failed;
      }else if(runningCount>0){
        info.status=DownloadTaskStatus.running;
        double percent=100*(1.0*successCount)/totalLength;
        info.progress=percent.toInt();
      }
    }
    return datas;
  }
  @override
  onCompleted(List data) async{

  }

  Future fetchImgDownloadUrl(String token,String group) async{
    try{
      var response=await OralRepository.fetchImgDownloadUrl(token, patientId, group);
      print("fetchImgDownloadUrl->downloadUrl=$response");
      return response;
    }
    catch(e,s){
      print("fetchImgDownloadUrl->e=$e");
      return null;
    }
  }
}

